/*
 * @Author: chen17
 * @Date: 2022-10-12 11:29:14
 * @LastEditTime: 2022-11-20 10:20:59
 * @Description: tasbar多标签页管理
 */

import router from '@/router'

const state = {
    tabRoutes: []
}

const mutations = {
    // 新增tab
    add_tab(state, route) {
        const target = state.tabRoutes.find(item => item.path === route.path)
        if (target) {
            if (route.fullPath !== target.fullPath) Object.assign(target, route)
            return
        }
        state.tabRoutes.push(Object.assign({}, route))
    },
    // 关闭tab
    del_tab(state, index) {
        state.tabRoutes.splice(index, 1)
    },
    // 关闭其他
    del_other(state, name) {
        state.tabRoutes = state.tabRoutes.filter(t => {
            return t.meta.affix || t.name === name
        })
    },
    // 关闭左侧
    del_left(state, name) {
        const index = state.tabRoutes.findIndex(item => item.name === name)
        state.tabRoutes = state.tabRoutes.filter((t, i) => {
            return t.meta.affix || i >= index
        })
    },
    // 关闭右侧
    del_right(state, name) {
        const index = state.tabRoutes.findIndex(item => item.name === name)
        state.tabRoutes = state.tabRoutes.filter((t, i) => {
            return t.meta.affix || i <= index
        })
    },
    // 关闭全部
    del_all(state) {
        const affixTabs = state.tabRoutes.filter(tab => tab.meta.affix)
        state.tabRoutes = affixTabs
    },
    // 重置
    reset_all(state) {
        state.tabRoutes = []
        console.log(state.tabRoutes, 'state.tabRoutes')
    }
}

const actions = {
    // 新增
    addTabRoute({ commit }, route) {
        commit('add_tab', route)
    },
    // 关闭 name：关闭的名称 isLast 是否选择上一个
    delTabRoute({ commit, state }, { name, isLast }) {
        let index = state.tabRoutes.findIndex(item => item.name === name)
        commit('del_tab', index)
        if (!isLast) return
        router.push({
            name: state.tabRoutes[index - 1].name
        })
    },
    // 操作关闭
    delTabRouteByCommand({ commit, state }, { type, name }) {
        if (type === 'all') {
            commit('del_all')
            router.push({
                name: state.tabRoutes[0].name
            })
        } else {
            commit(`del_${type}`, name)
        }
    },
    // 重置tabs
    resetTabRoute({ commit }) {
        commit('reset_all', [])
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
